package com.example.zhilierp.exception;

import com.example.zhilierp.util.Result;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.context.request.WebRequest;
import java.time.LocalDateTime;

/**
 * 全局异常处理器
 * 捕获并处理系统中的所有异常
 */
@RestControllerAdvice
public class GlobalExceptionHandler {
    
    /**
     * 处理业务异常
     */
    @ExceptionHandler(BusinessException.class)
    public Result<String> handleBusinessException(BusinessException ex, WebRequest request) {
        // 记录业务异常日志
        System.err.println("业务异常: " + ex.getMessage());
        // 使用只包含消息的error方法
        return Result.error(ex.getMessage());
    }
    
    /**
     * 处理系统异常
     */
    @ExceptionHandler(Exception.class)
    public Result<String> handleGlobalException(Exception ex, WebRequest request) {
        // 记录异常日志
        ex.printStackTrace();
        return Result.error("系统内部错误，请联系管理员");
    }
    
    /**
     * 处理空指针异常
     */
    @ExceptionHandler(NullPointerException.class)
    public Result<String> handleNullPointerException(NullPointerException ex, WebRequest request) {
        // 记录异常日志
        ex.printStackTrace();
        return Result.error("系统发生空指针异常");
    }
    
    /**
     * 处理参数异常
     */
    @ExceptionHandler(IllegalArgumentException.class)
    public Result<String> handleIllegalArgumentException(IllegalArgumentException ex, WebRequest request) {
        // 记录异常日志
        System.err.println("参数异常: " + ex.getMessage());
        return Result.error(ex.getMessage());
    }
}